package com.haiyang.auth.config;

import com.haiyang.auth.model.PermissionEntity;
import com.haiyang.auth.service.SysRoleService;
import com.haiyang.auth.service.impl.OidcUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
import org.springframework.security.oauth2.core.oidc.endpoint.OidcParameterNames;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.token.JwtEncodingContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenCustomizer;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @BelongsProject: ms
 * @BelongsPackage: com.haiyang.auth.config
 * @Author: BHY
 * @CreateTime: 2023-10-31  08:49
 * @Description: token增强
 * @Version: 1.0
 */
@Configuration(proxyBeanMethods = false)
public class AccessTokenCustomizerConfig {

    @Autowired
    SysRoleService sysRoleService;
    @Autowired
    OidcUserInfoService userInfoService;

    @Bean
    public OAuth2TokenCustomizer<JwtEncodingContext> tokenCustomizer() {
        return (context) -> {
            System.out.println(context.getPrincipal().getAuthorities());
            //access_token 自定义claim Object
            if (OAuth2TokenType.ACCESS_TOKEN.equals(context.getTokenType())) {
                context.getClaims().claims(claim -> {
                    Set<String> collect = context.getPrincipal().getAuthorities().stream()
                            .map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
                    claim.put("authorities",sysRoleService.findByRoleCode(collect).stream().map(PermissionEntity::getPermissionCode).collect(Collectors.toSet()));
                });
            }
            //id_token 自定义claim Object
            if (OidcParameterNames.ID_TOKEN.equals(context.getTokenType().getValue())) {
                context.getClaims().claims(claim -> {
                    Set<String> collect = context.getPrincipal().getAuthorities().stream()
                            .map(GrantedAuthority::getAuthority).collect(Collectors.toSet());
                    claim.put("authorities", sysRoleService.findByRoleCode(collect).stream().map(PermissionEntity::getPermissionCode).collect(Collectors.toSet()));
                });
            }
        };
    }
}
